package com.anjian.bamin.anjiandianzimap.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.aiton.administrator.shane_library.shane.ZjbBaseActivity;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.navi.AMapNavi;
import com.amap.api.navi.AMapNaviListener;
import com.amap.api.navi.enums.PathPlanningStrategy;
import com.amap.api.navi.model.AMapLaneInfo;
import com.amap.api.navi.model.AMapNaviCross;
import com.amap.api.navi.model.AMapNaviInfo;
import com.amap.api.navi.model.AMapNaviLocation;
import com.amap.api.navi.model.AMapNaviPath;
import com.amap.api.navi.model.AMapNaviTrafficFacilityInfo;
import com.amap.api.navi.model.AimLessModeCongestionInfo;
import com.amap.api.navi.model.AimLessModeStat;
import com.amap.api.navi.model.NaviInfo;
import com.amap.api.navi.model.NaviLatLng;
import com.amap.api.navi.view.RouteOverLay;
import com.anjian.bamin.anjiandianzimap.R;
import com.anjian.bamin.anjiandianzimap.TTSController;
import com.anjian.bamin.anjiandianzimap.contant.Constant;
import com.anjian.bamin.anjiandianzimap.model.CompanyInfo;
import com.autonavi.tbt.TrafficFacilityInfo;
import com.blankj.utilcode.utils.ToastUtils;

import java.util.ArrayList;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.anjian.bamin.anjiandianzimap.TTSController.ttsManager;

public class NavigateActivity extends ZjbBaseActivity implements AMapNaviListener {

    @Bind(R.id.imgBack)
    ImageView mImgBack;
    @Bind(R.id.textView_companyName)
    TextView mTextViewCompanyName;
    @Bind(R.id.textView_Address)
    TextView mTextViewAddress;
    @Bind(R.id.button_daoHang)
    ImageView mButtonDaoHang;
    @Bind(R.id.map)
    MapView mMap;
    private CompanyInfo mCompanyInfo;

    private LatLng mLocationLatLng;
    //声明定位回调监听器
    public AMapLocationListener mLocationListener = new AMapLocationListener() {


        @Override
        public void onLocationChanged(AMapLocation amapLocation) {
            showLoadingDialog();
            if (amapLocation != null) {
                if (amapLocation.getErrorCode() == 0) {
                    //定位成功回调信息，设置相关消息
                    double latitude = amapLocation.getLatitude();//获取纬度
                    double longitude = amapLocation.getLongitude();//获取经度
                    cancelLoadingDialog();
                    //设置上车地址
                    mLocationLatLng = new LatLng(latitude,
                            longitude);
                    moveCenterMarker(mLocationLatLng);
                    initMap();

                } else {
                    //显示错误信息ErrCode是错误码，errInfo是错误信息，详见错误码表。
                    Log.e("AmapError", "location Error, ErrCode:"
                            + amapLocation.getErrorCode() + ", errInfo:"
                            + amapLocation.getErrorInfo());
                }
            }
        }

    };
    private MarkerOptions mMarkerOptions;
    private AMapNavi aMapNavi;
    private AMap mAMap;
    private RouteOverLay mRouteOverLay;
    private AMapLocationClient mLocationClient;
    private AMapLocationClientOption mLocationOption;
    private Marker mMarker;
    // 起点终点列表
    private ArrayList<NaviLatLng> mStartPoints = new ArrayList<NaviLatLng>();
    private ArrayList<NaviLatLng> mEndPoints = new ArrayList<NaviLatLng>();
    private NaviLatLng mEnd;
    private NaviLatLng mDriverNaviLatLng;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_navigate);
        ButterKnife.bind(this);
        ttsManager = TTSController.getInstance(this);
        ttsManager.init();
        aMapNavi = AMapNavi.getInstance(this);
        aMapNavi.addAMapNaviListener(this);
        aMapNavi.addAMapNaviListener(ttsManager);
        aMapNavi.setEmulatorNaviSpeed(150);//设置模拟导航的速度
        mMap = (MapView) findViewById(R.id.map);
        //在activity执行onCreate时执行mMapView.onCreate(savedInstanceState)，实现地图生命周期管理
        mMap.onCreate(savedInstanceState);
        mAMap = mMap.getMap();
        mRouteOverLay = new RouteOverLay(mAMap, null, getApplicationContext());

        //设置默认定位按钮是否显示
        UiSettings uiSettings = mAMap.getUiSettings();
        uiSettings.setMyLocationButtonEnabled(false);
        uiSettings.setZoomControlsEnabled(false);//设置了地图是否允许显示缩放按钮

        // 设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false
        mAMap.setMyLocationEnabled(true);
        //返回一个CameraUpdate 对象，改变了当前可视区域的zoom 级别
        mAMap.moveCamera(CameraUpdateFactory.zoomBy(6));
        //初始化定位
        mLocationClient = new AMapLocationClient(getApplicationContext());
        //设置定位回调监听
        mLocationClient.setLocationListener(mLocationListener);
        //初始化定位参数
        mLocationOption = new AMapLocationClientOption();
        //设置定位模式为高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //设置是否返回地址信息（默认返回地址信息）
        mLocationOption.setNeedAddress(true);
        //设置是否只定位一次,默认为false
        mLocationOption.setOnceLocation(true);
        //设置是否强制刷新WIFI，默认为强制刷新
        mLocationOption.setWifiActiveScan(true);
        //设置是否允许模拟位置,默认为false，不允许模拟位置
        mLocationOption.setMockEnable(false);
        //设置定位间隔,单位毫秒,默认为2000ms
        mLocationOption.setInterval(5000);
        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);
        //启动定位
        showLoadingDialog();
        mLocationClient.startLocation();
        init();
    }

    public static Intent newIntent(Context context, CompanyInfo companyInfo) {
        Intent intent = new Intent(context, NavigateActivity.class);
        intent.putExtra(Constant.INTENT_KEY.COMPANYINFO, companyInfo);
        return intent;
    }

    @Override
    protected void initSP() {

    }

    @Override
    protected void initIntent() {
        mCompanyInfo = (CompanyInfo) getIntent().getSerializableExtra(Constant.INTENT_KEY.COMPANYINFO);

    }

    @Override
    protected void initData() {
        double companyLat = mCompanyInfo.getCompanyLat();
        double companyLng = mCompanyInfo.getCompanyLng();
        mEnd = new NaviLatLng(companyLat, companyLng);

    }

    @Override
    protected void findID() {

    }

    @Override
    protected void initViews() {
    }

    private void initMap() {
        mTextViewCompanyName.setText("企业:"+mCompanyInfo.getCompanyName());
        mTextViewAddress.setText("地址:"+mCompanyInfo.getCompanyAddress());

        mDriverNaviLatLng = new NaviLatLng(mLocationLatLng.latitude, mLocationLatLng.longitude);

        calculateDriveRoute();
    }

    @Override
    protected void setListeners() {

    }

    @OnClick({R.id.imgBack, R.id.button_daoHang})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.imgBack:
                finishTo();
                break;

            case R.id.button_daoHang:
                Intent intent = GPSNaviActivity.newIntent(this, mEnd);
                startActivityTo(intent);
                break;
        }
    }

    private void moveCenterMarker(LatLng latLng) {
        mMarkerOptions = new MarkerOptions();
        mMarkerOptions.icon(BitmapDescriptorFactory.fromResource(R.mipmap.map_marker));
        mMarkerOptions.position(latLng);
        if (mMarker != null) {
            mMarker.destroy();
        }
        mMarker = mAMap.addMarker(mMarkerOptions);
        //返回一个CameraUpdate对象，只改变地图可视区域中心点，地图缩放级别不变
        mAMap.moveCamera(CameraUpdateFactory.changeLatLng(latLng));
    }
    /**
     * 计算驾车路线
     */
    private void calculateDriveRoute() {
        mStartPoints.clear();
        mEndPoints.clear();
        mStartPoints.add(mDriverNaviLatLng);
        mEndPoints.add(mEnd);
        moveCenterMarker(new LatLng(mDriverNaviLatLng.getLatitude(), mDriverNaviLatLng.getLongitude()));
        boolean isSuccess = aMapNavi.calculateDriveRoute(mStartPoints,
                mEndPoints, null, PathPlanningStrategy.DRIVING_DEFAULT);
        if (!isSuccess) {
            ToastUtils.showShortToast(this,"路线计算失败,检查参数情况");
        }
    }

    @Override
    public void onInitNaviFailure() {

    }

    @Override
    public void onInitNaviSuccess() {

    }

    @Override
    public void onStartNavi(int i) {

    }

    @Override
    public void onTrafficStatusUpdate() {

    }

    @Override
    public void onLocationChange(AMapNaviLocation aMapNaviLocation) {

    }

    @Override
    public void onGetNavigationText(int i, String s) {

    }

    @Override
    public void onEndEmulatorNavi() {

    }

    @Override
    public void onArriveDestination() {

    }

    @Override
    public void onCalculateRouteSuccess() {
        AMapNaviPath naviPath = aMapNavi.getNaviPath();
        if (naviPath == null) {
            return;
        }
        // 获取路径规划线路，显示到地图上
        mRouteOverLay.setAMapNaviPath(naviPath);
        mRouteOverLay.addToMap();
    }
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        //在activity执行onSaveInstanceState时执行mMapView.onSaveInstanceState (outState)，实现地图生命周期管理
        mMap.onSaveInstanceState(outState);
    }
    @Override
    protected void onResume() {
        super.onResume();
        //在activity执行onResume时执行mMapView.onResume ()，实现地图生命周期管理
        mMap.onResume();
        mStartPoints.add(mDriverNaviLatLng);
        mEndPoints.add(mEnd);
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        //在activity执行onDestroy时执行mMapView.onDestroy()，实现地图生命周期管理
        mMap.onDestroy();
        aMapNavi.destroy();
        ttsManager.destroy();
//        unregisterReceiver(receiver);
    }
    @Override
    protected void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView.onPause ()，实现地图生命周期管理
        mMap.onPause();
    }
    @Override
    public void onCalculateRouteFailure(int i) {
        ToastUtils.showShortToast(this,"路径规划出错" + i);
    }

    @Override
    public void onReCalculateRouteForYaw() {

    }

    @Override
    public void onReCalculateRouteForTrafficJam() {

    }

    @Override
    public void onArrivedWayPoint(int i) {

    }

    @Override
    public void onGpsOpenStatus(boolean b) {

    }

    @Override
    public void onNaviInfoUpdated(AMapNaviInfo aMapNaviInfo) {

    }

    @Override
    public void onNaviInfoUpdate(NaviInfo naviInfo) {

    }

    @Override
    public void OnUpdateTrafficFacility(AMapNaviTrafficFacilityInfo aMapNaviTrafficFacilityInfo) {

    }

    @Override
    public void OnUpdateTrafficFacility(TrafficFacilityInfo trafficFacilityInfo) {

    }

    @Override
    public void showCross(AMapNaviCross aMapNaviCross) {

    }

    @Override
    public void hideCross() {

    }

    @Override
    public void showLaneInfo(AMapLaneInfo[] aMapLaneInfos, byte[] bytes, byte[] bytes1) {

    }

    @Override
    public void hideLaneInfo() {

    }

    @Override
    public void onCalculateMultipleRoutesSuccess(int[] ints) {

    }

    @Override
    public void notifyParallelRoad(int i) {

    }

    @Override
    public void OnUpdateTrafficFacility(AMapNaviTrafficFacilityInfo[] aMapNaviTrafficFacilityInfos) {

    }

    @Override
    public void updateAimlessModeStatistics(AimLessModeStat aimLessModeStat) {

    }

    @Override
    public void updateAimlessModeCongestionInfo(AimLessModeCongestionInfo aimLessModeCongestionInfo) {

    }
}
